package com.smartum.mpr.business;

import java.util.Calendar;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.smartum.mpr.dao.ItemCategoryDao;
import com.smartum.mpr.dao.ItemPurchaseDao;
import com.smartum.mpr.dao.JobCategoryDao;
import com.smartum.mpr.dao.JobPurchaseDao;
import com.smartum.mpr.exception.AuthorizationException;
import com.smartum.mpr.exception.DatabaseIntegrityException;
import com.smartum.mpr.exception.NotExistsCategoryException;
import com.smartum.mpr.exception.NotExistsTokenException;
import com.smartum.mpr.model.ItemCategory;
import com.smartum.mpr.model.ItemPurchase;
import com.smartum.mpr.model.JobCategory;
import com.smartum.mpr.model.JobPurchase;
import com.smartum.mpr.model.User;

@Service
public class PurchaseBusiness extends BaseBusiness {

	@Autowired
	private ItemPurchaseDao itemPurchaseDao;
	@Autowired
	private JobPurchaseDao jobPurchaseDao;

	@Autowired
	private ItemCategoryDao itemCategoryDao;
	@Autowired
	private JobCategoryDao jobCategoryDao;

	@Autowired
	private UserBusiness userBusiness;

	public void saveItemPurchase(String token, long categoryId, long receiptId, String transactionReceipt)
	        throws DatabaseIntegrityException, AuthorizationException, NotExistsTokenException, NotExistsCategoryException {
		User user = userBusiness.getUserByToken(token);

		ItemCategory category = itemCategoryDao.get(categoryId);
		if (category == null) {
			throw new NotExistsCategoryException();
		}
		
		ItemPurchase purchase = new ItemPurchase();
		purchase.setUser(user);
		purchase.setReceiptId(receiptId);
		purchase.setTransactionReceipt(transactionReceipt);
		purchase.setCategory(category);

		itemPurchaseDao.save(purchase);
	}

	public void saveJobPurchase(String token, long categoryId, long receiptId, String transactionReceipt)
	        throws DatabaseIntegrityException, AuthorizationException, NotExistsTokenException,
	        NotExistsCategoryException {
		User user = userBusiness.getUserByToken(token);

		JobCategory category = jobCategoryDao.get(categoryId);
		if (category == null) {
			throw new NotExistsCategoryException();
		}

		JobPurchase purchase = new JobPurchase();
		purchase.setUser(user);
		purchase.setReceiptId(receiptId);
		purchase.setTransactionReceipt(transactionReceipt);
		purchase.setCategory(category);

		jobPurchaseDao.save(purchase);
	}

}
